﻿#include "MainWindow.h"
#include "ui_MainWindow.h"

#include "qdebug.h"
#include <qdatetime.h>
#include <qtimer.h>
#include <qnetworkdatagram.h>
#include <qudpsocket.h>
#include <qmessagebox.h>
#include <qevent.h>

#include "ReadMEMSDataCodec_Client.h"
#include "TcpIOer.h"
#include "TcpCodec_Transmit.h"
#include "MCUCodec_SetInterval_MEMSData.h"
#include "UserRegisterCodec.h"
#include "DeviceInfoManager.h"
#include "UserInfoCodec.h"

//ui
#include "MemsAutoTestSoftware.h"
#include "DialogLogin.h"

#include "MacroDefinition.h"

MainWindow::MainWindow(QWidget *parent)
  : QMainWindow(parent)
  , ui(new Ui::MainWindow)
{
  ui->setupUi(this);
  setFixedSize(size());
  tableWidget_deviceList=ui->tableWidget_deviceList;
  transmitResult.append(QStringLiteral("指令下发成功"));
  transmitResult.append(QStringLiteral("正在下发指令"));
  transmitResult.append(QStringLiteral("指令下发失败，前一条指令正在下发"));
  transmitResult.append(QStringLiteral("指令下发失败，目标设备已离线"));
  transmitResult.append(QStringLiteral("指令下发失败，指令下发超时"));
  transmitResult.append(QStringLiteral("指令下发失败，指令数据错误"));
  init();
}

MainWindow::~MainWindow()
{
  delete ui;
}

void MainWindow::slot_showData(int dataGroupIndex, QByteArray data)
{

}

void MainWindow::closeEvent(QCloseEvent * closeEvent)
{
  if(QMessageBox::question(this,QStringLiteral("退出"),QStringLiteral("确定要退出吗？"))==QMessageBox::Yes)
    {
      closeEvent->accept();
    }
  else
    {
      closeEvent->ignore();
    }
}

void MainWindow::showEvent(QShowEvent * showEvent)
{
  userInfoCodec->getAllDeviceFromServer();
  deviceInfoManager->startTimer_allDevice(2000);
  QMainWindow::showEvent(showEvent);
}

void MainWindow::hideEvent(QHideEvent * hideEvent)
{
  deviceInfoManager->stopTimer_allDevice();
  QMainWindow::hideEvent(hideEvent);
}

void MainWindow::slot_MEMSData_readAll(QVector<MEMSData> list)
{

}

void MainWindow::slot_showAllDevice()
{
  if(!isVisible())
    {
      return;
    }
  QVector<Device>* deviceInfoList=deviceInfoManager->getDeviceInfoList();
  int count=tableWidget_deviceList->rowCount();
  int currentRow=tableWidget_deviceList->currentRow();
  for(int i=0;i<count;++i)
    {
      tableWidget_deviceList->removeRow(0);
    }
  count=deviceInfoList->size();
  tableWidget_deviceList->setRowCount(count);
  for(int i=0;i<count;++i)
    {

      Device& device=(*deviceInfoList)[i];
      tableWidget_deviceList->setItem(i,0,makeTableWidgetItem(QString::number(device.getDeviceId())));
      if(device.getHostAddress()==0)
        {
          tableWidget_deviceList->setItem(i,1,makeTableWidgetItem(QStringLiteral("离线")));
          tableWidget_deviceList->setItem(i,2,makeTableWidgetItem("---"));
          tableWidget_deviceList->setItem(i,3,makeTableWidgetItem("---"));
          tableWidget_deviceList->setItem(i,4,makeTableWidgetItem("---"));
          tableWidget_deviceList->setItem(i,5,makeTableWidgetItem("---"));
        }
      else
        {
          tableWidget_deviceList->setItem(i,1,makeTableWidgetItem(QStringLiteral("在线")));
          tableWidget_deviceList->setItem(i,2,makeTableWidgetItem(device.getTurnTable_runningState_power()?QStringLiteral("上电"):QStringLiteral("下电")));
          tableWidget_deviceList->setItem(i,3,makeTableWidgetItem(device.getTurnTable_runningState_circuit()?QStringLiteral("闭合"):QStringLiteral("闲置")));
          tableWidget_deviceList->setItem(i,4,makeTableWidgetItem(device.getTurnTable_runningState_amplifier()?QStringLiteral("异常"):QStringLiteral("正常")));
          tableWidget_deviceList->setItem(i,5,makeTableWidgetItem(device.getTurnTable_runningState_running()?QStringLiteral("运行"):QStringLiteral("停止")));
        }
    }
  tableWidget_deviceList->setCurrentCell(currentRow,0);
}

void MainWindow::slot_showResult(uchar result)
{
  showMessage(tcpCodec_Transmit->getResultMessage(result));
}

void MainWindow::slot_logout()
{
  userRegisterCodec->logout();
  hide();
  dialogLogin->show();
}

void MainWindow::slot_pushButton_test()
{
  int row=tableWidget_deviceList->currentRow();
  if(0>row||tableWidget_deviceList->rowCount()<=row)
    {
      QMessageBox::information(this,QStringLiteral("提示"),QStringLiteral("请选中一个设备"));
      return;
    }
  if(tableWidget_deviceList->item(row,1)->text()==QStringLiteral("离线"))
    {
      QMessageBox::information(this,QStringLiteral("提示"),QStringLiteral("选中的设备已经离线"));
      return;
    }
  bool ok=false;
  ushort interval=ui->lineEdit_test->text().toUShort(&ok);
  if(ok)
    {
      mCUCodec_SetInterval_MEMSData->setInterval(tableWidget_deviceList->item(row,0)->text().toUInt(),interval);
    }
}

void MainWindow::slot_cellDoubleClicked(int row, int column)
{
  if(tableWidget_deviceList->item(row,1)->text()==QStringLiteral("离线"))
    {
      QMessageBox::information(this,QStringLiteral("消息"),QStringLiteral("目标设备已经离线"));
      return;
    }
  hide();
  memsAutoTestSoftware->showDevice(tableWidget_deviceList->item(row,0)->text().toUInt());
}

void MainWindow::init()
{
  connect(ui->pushButton_test,&QPushButton::clicked,this,&MainWindow::slot_pushButton_test);
  connect(tableWidget_deviceList,&QTableWidget::cellDoubleClicked,this,&MainWindow::slot_cellDoubleClicked);
  connect(ui->action_user_logout,&QAction::triggered,this,&MainWindow::slot_logout);
}

void MainWindow::showMessage(QString msg)
{
  QListWidget* listWidget = ui->listWidget_message;
  listWidget->addItem(QDateTime::currentDateTime().toString("yyyy" + QStringLiteral("年") + "MM" + QStringLiteral("月") + "dd" + QStringLiteral("日") + "  hh:mm:ss  ") + msg);
  listWidget->setCurrentRow(listWidget->count() - 1);
  if (listWidget->count() > 100)
    {//if the count of listWidget's item over 100
      listWidget->takeItem(0);//remove the first one
    }
}

QTableWidgetItem* MainWindow::makeTableWidgetItem(QString text)
{
  QTableWidgetItem*item=new QTableWidgetItem();
  item->setText(text);
  item->setTextAlignment(Qt::AlignCenter);
  return item;
}

ReadMEMSDataCodec_Client* MainWindow::getReadMEMSDataCodec_Client()
{
  return readMEMSDataCodec_Client;
}

MainWindow *MainWindow::setReadMEMSDataCodec_Client(ReadMEMSDataCodec_Client* readMEMSDataCodec_Client)
{
  if(Q_NULLPTR!=this->readMEMSDataCodec_Client)
    {
      disconnect(this->readMEMSDataCodec_Client,&ReadMEMSDataCodec_Client::signal_readAll,this,&MainWindow::slot_MEMSData_readAll);
    }
  this->readMEMSDataCodec_Client=readMEMSDataCodec_Client;
  printInjection(this,readMEMSDataCodec_Client);
  connect(this->readMEMSDataCodec_Client,&ReadMEMSDataCodec_Client::signal_readAll,this,&MainWindow::slot_MEMSData_readAll);
  return this;
}

TcpIOer* MainWindow::getTcpIOer()
{
  return tcpIOer;
}

MainWindow *MainWindow::setTcpIOer(TcpIOer* tcpIOer)
{
  this->tcpIOer=tcpIOer;
  printInjection(this,tcpIOer);
  return this;
}

TcpCodec_Transmit* MainWindow::getTcpCodec_Transmit()const
{
  return tcpCodec_Transmit;
}

MainWindow* MainWindow::setTcpCodec_Transmit(TcpCodec_Transmit* const tcpCodec_Transmit)
{
  if(Q_NULLPTR!=this->tcpCodec_Transmit)
    {
      disconnect(this->tcpCodec_Transmit,&TcpCodec_Transmit::signal_result,this,&MainWindow::slot_showResult);
    }
  this->tcpCodec_Transmit=tcpCodec_Transmit;
  connect(this->tcpCodec_Transmit,&TcpCodec_Transmit::signal_result,this,&MainWindow::slot_showResult);
  printInjection(this,tcpCodec_Transmit);
  return this;
}

MCUCodec_SetInterval_MEMSData* MainWindow::setMCUCodec_SetInterval_MEMSData()const
{
  return mCUCodec_SetInterval_MEMSData;
}

MainWindow* MainWindow::setMCUCodec_SetInterval_MEMSData(MCUCodec_SetInterval_MEMSData* const mCUCodec_SetInterval_MEMSData)
{
  this->mCUCodec_SetInterval_MEMSData=mCUCodec_SetInterval_MEMSData;
  return this;
}

UserRegisterCodec* MainWindow::getUserRegisterCodec()const
{
  return userRegisterCodec;
}

MainWindow* MainWindow::setUserRegisterCodec(UserRegisterCodec*const userRegisterCodec)
{
  this->userRegisterCodec=userRegisterCodec;
  printInjection(this,userRegisterCodec);
  return this;
}

DeviceInfoManager* MainWindow::getDeviceInfoManager()const
{
  return deviceInfoManager;
}

MainWindow* MainWindow::setDeviceInfoManager(DeviceInfoManager* const deviceInfoManager)
{
  if(Q_NULLPTR!=deviceInfoManager)
    {
      disconnect(deviceInfoManager,&DeviceInfoManager::signal_newAllDeviceInfo,this,&MainWindow::slot_showAllDevice);
    }
  this->deviceInfoManager=deviceInfoManager;
  if(Q_NULLPTR!=deviceInfoManager)
    {
      connect(deviceInfoManager,&DeviceInfoManager::signal_newAllDeviceInfo,this,&MainWindow::slot_showAllDevice);
    }
  printInjection(this,deviceInfoManager);
  return this;
}

UserInfoCodec* MainWindow::getUserInfoCodec()const
{
  return userInfoCodec;
}

MainWindow* MainWindow::setUserInfoCodec(UserInfoCodec*const userInfoCodec)
{
  this->userInfoCodec=userInfoCodec;
  printInjection(this,userInfoCodec);
  return this;
}

MemsAutoTestSoftware* MainWindow::getMemsAutoTestSoftware()const
{
  return memsAutoTestSoftware;
}

MainWindow* MainWindow::setMemsAutoTestSoftware(MemsAutoTestSoftware*const memsAutoTestSoftware)
{
  this->memsAutoTestSoftware=memsAutoTestSoftware;
  printInjection(this,memsAutoTestSoftware);
  return this;
}
DialogLogin* MainWindow::getDialogLogin()const
{
  return dialogLogin;
}

MainWindow* MainWindow::setDialogLogin(DialogLogin*const dialogLogin)
{
  this->dialogLogin=dialogLogin;
  printInjection(this,dialogLogin);
  return this;
}

void MainWindow::objectAutoInjection(QHash<QString, QObject *> *objMap)
{
  //act
  setReadMEMSDataCodec_Client(getObjFromMap<ReadMEMSDataCodec_Client>(objMap));
  setTcpIOer(getObjFromMap<TcpIOer>(objMap));
  setTcpCodec_Transmit(getObjFromMap<TcpCodec_Transmit>(objMap));
  setMCUCodec_SetInterval_MEMSData(getObjFromMap<MCUCodec_SetInterval_MEMSData>(objMap));
  setUserRegisterCodec(getObjFromMap<UserRegisterCodec>(objMap));
  setDeviceInfoManager(getObjFromMap<DeviceInfoManager>(objMap));
  setUserInfoCodec(getObjFromMap<UserInfoCodec>(objMap));

  //ui
  setMemsAutoTestSoftware(getObjFromMap<MemsAutoTestSoftware>(objMap));
  setDialogLogin(getObjFromMap<DialogLogin>(objMap));
}
